package forkjoinpooldemo;

import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

/**
 * @author chaird
 * @create 2022-04-27 10:20
 */
public class App {
  public static void main(String[] args) {
    int[] data = {1, 23, 46, 7, 89, 43, 67};
    ForkJoinPool forkJoinPool = new ForkJoinPool();
    MyTask myTask = new MyTask(data);
    forkJoinPool.invoke(myTask);
    Integer res = myTask.join();
    System.out.println(res);
  }
}

class MyTask extends RecursiveTask<Integer> {
  int[] data;

  public MyTask(int[] data) {
    this.data = data;
  }

  @Override
  protected Integer compute() {
    try { TimeUnit.SECONDS.sleep(5); } catch (Exception e) { e.printStackTrace(); } finally { }
    if (data.length == 1) {
      return data[0];
    }
    if (data.length == 2) {
      return Math.max(data[0], data[1]);
    }
    int mid = data.length / 2;
    MyTask lefttask = new MyTask(Arrays.copyOf(data, mid));
    MyTask righttask = new MyTask(Arrays.copyOfRange(data, mid, data.length));
    invokeAll(lefttask, righttask);
    Integer leftValue = lefttask.join();
    Integer rightValue = righttask.join();
    return Math.max(leftValue, rightValue);
  }
}
